package com.jus.player.api;

import static com.jus.player.config.AppConfig.INT_5;
import static com.jus.player.util.CommonUtils.logout;
import static com.jus.player.util.CommonUtils.navigateTo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;

import androidx.annotation.NonNull;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.jus.player.activity.LoginActivity;
import com.jus.player.config.AppConfig;
import com.jus.player.config.HttpStatusEnum;
import com.jus.player.util.CommonUtils;

import java.io.File;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.nio.Buffer;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;

import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.ConnectionPool;
import okhttp3.Dns;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 终极优化版OkHttp封装工具类
 * 功能：
 * 1. 自动重试机制（最大3次）
 * 2. 完善的资源释放
 * 3. 精细化异常分类处理
 * 4. 支持GET/POST/文件上传
 * 5. 自定义公共参数拦截器
 * 6. 连接池优化
 */
public final class OkHttpHelper {

    @SuppressLint("StaticFieldLeak")
    private static volatile OkHttpHelper instance;
    private OkHttpClient client;
    private final Activity appContext;
    public static final String _TOKEN = "token";
    public static final String _CODE = "code";
    public static final String _DATA = "data";
    public static final String _RECORD = "record";
    public static final String _TOTAL = "total";

    // 私有构造方法
    private OkHttpHelper(Activity context) {
        this.appContext = context;
        initOkHttpClient();
    }

    // 获取单例
    public static OkHttpHelper getInstance(Activity context) {
        if (instance == null) {
            synchronized (OkHttpHelper.class) {
                if (instance == null) {
                    instance = new OkHttpHelper(context);
                }
            }
        }
        return instance;
    }

    // 初始化OkHttpClient
    private void initOkHttpClient() {
        this.client = new OkHttpClient.Builder()
                .addInterceptor(new RetryInterceptor(INT_5, 1000))// 最大重试5次，基础延迟1s
                .connectionPool(new ConnectionPool(5, 5, TimeUnit.MINUTES))
                .callTimeout(AppConfig.INT_60, TimeUnit.SECONDS)// 总超时（包括重定向、重试）
                .connectTimeout(AppConfig.INT_10, TimeUnit.SECONDS)
                .readTimeout(AppConfig.INT_20, TimeUnit.SECONDS)
                .writeTimeout(AppConfig.INT_20, TimeUnit.SECONDS)
                .retryOnConnectionFailure(false) //OkHttp自带重试,禁用默认重试，用我们的拦截器
                //.dns(new CustomDns(AppConfig.INT_5))

                .addInterceptor(new CommonParamsInterceptor(appContext)) // 公共参数拦截器
                .addInterceptor(new NetworkCheckInterceptor(appContext))
                .connectionPool(new ConnectionPool(INT_5, INT_5, TimeUnit.MINUTES))// 连接池优化
                .build();
        //.addInterceptor(new LoggingInterceptor()); // 日志拦截器
        // 设置全局日期格式为 ISO 格式（不带毫秒）
        JSON.configWriterDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        // 调试模式下添加详细日志
        /*if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(logging);
        }*/
    }

    // ==================== 请求方法封装 ====================

    /**
     * 异步GET请求
     */
    public void getAsync(String url, Map<String, String> params, final HttpCallback callback) {
        url = ApiConfig.BASE_URL + url;
        Request request = buildGetRequest(url, params);
        executeAsync(request, callback);
    }

    /**
     * 同步GET请求
     */
    public String getSync(String url, Map<String, String> params) throws HttpException {
        url = ApiConfig.BASE_URL + url;
        Request request = buildGetRequest(url, params);
        return executeSync(request);
    }

    /**
     * 异步POST表单请求
     */
    public void postFormAsync(String url, Map<String, String> params, HttpCallback callback) {
        url = ApiConfig.BASE_URL + url;
        Request request = buildPostFormRequest(url, params);
        executeAsync(request, callback);
    }

    /**
     * 异步POST JSON请求
     */
    public void postJsonAsync(String url, String json, HttpCallback callback) {
        url = ApiConfig.BASE_URL + url;
        Request request = buildPostJsonRequest(url, json);
        executeAsync(request, callback);
    }

    /**
     * 异步POST JSON请求
     */
    public void postJsonAsync(String url, Map<String, Object> params, HttpCallback callback) {
        url = ApiConfig.BASE_URL + url;
        String jsonString = JSON.toJSONString(params);
        Log.e("网络请求（postJsonAsync）参数", jsonString);
        Request request = buildPostJsonRequest(url, jsonString);
        executeAsync(request, callback);
    }

    /**
     * 异步POST多部分请求（文件上传）
     */
    public void postMultipartAsync(String url,
                                   Map<String, String> params,
                                   Map<String, File> files,
                                   HttpCallback callback) {
        url = ApiConfig.BASE_URL + url;
        Request request = buildMultipartRequest(url, params, files);
        executeAsync(request, callback);
    }

    // ==================== 请求构建方法 ====================

    private Request buildGetRequest(String url, Map<String, String> params) {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                urlBuilder.addQueryParameter(entry.getKey(), entry.getValue());
            }
        }
        return new Request.Builder()
                .url(urlBuilder.build())
                .get()
                .build();
    }

    private Request buildPostFormRequest(String url, Map<String, String> params) {
        FormBody.Builder builder = new FormBody.Builder();
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (entry.getValue() != null) {
                    builder.add(entry.getKey(), entry.getValue());
                }
            }
        }
        return new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
    }

    private Request buildPostJsonRequest(String url, String json) {
        MediaType mediaType = MediaType.parse(AppConfig.MEDIA_TYPE_JSON);
        RequestBody body = RequestBody.create(json, mediaType);
        return new Request.Builder()
                .url(url)
                .post(body)
                .build();
    }

    private Request buildMultipartRequest(String url,
                                          Map<String, String> params,
                                          Map<String, File> files) {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);

        // 添加文本参数
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.addFormDataPart(entry.getKey(), entry.getValue());
            }
        }

        // 添加文件参数
        if (files != null) {
            for (Map.Entry<String, File> entry : files.entrySet()) {
                File file = entry.getValue();
                if (file != null && file.exists()) {
                    RequestBody fileBody = RequestBody.create(
                            MediaType.parse("application/octet-stream"),
                            file
                    );
                    builder.addFormDataPart(
                            entry.getKey(),
                            file.getName(),
                            fileBody
                    );
                }
            }
        }

        return new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
    }

    // ==================== 请求执行方法 ====================

    private void executeAsync(Request request, final HttpCallback callback) {
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                // 所有重试已耗尽，最终失败才提示
                if (callback != null && !call.isCanceled()) {
                    Log.e(">>>网络请求异常", "异常信息：" + e.getMessage() + " 请求地址：" + request.url().url());
                    HttpException httpException = handleException(e);
                    callback.onFailure(httpException);
                }
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                try {
                    if (!response.isSuccessful()) {
                        // HTTP状态码错误也走重试逻辑（通过拦截器）
                        handleUnsuccessfulResponse(response, callback);
                        return;
                    }
                    String result = response.body() == null ? "" : response.body().string();
                    handleSuccessfulResponse(result, callback);
                } catch (IOException e) {
                    if (callback != null) {
                        callback.onFailure(new HttpException(-1, "数据解析错误"));
                    }
                } finally {
                    // 确保资源释放
                    response.close();
                    if (!call.isCanceled()) {
                        call.cancel();
                    }
                }
            }
        });
    }

    // 集中处理失败响应
    private void handleUnsuccessfulResponse(Response response, HttpCallback callback) {
        try {
            String errorBody = response.body() != null ? response.body().string() : "";
            JSONObject errorJson = JSONObject.parseObject(errorBody);
            String errorMsg = errorJson != null ?
                    errorJson.getString("message") : "HTTP " + response.code();

            if (callback != null) {
                callback.onFailure(new HttpException(response.code(), errorMsg));
            }
        } catch (IOException e) {
            if (callback != null) {
                callback.onFailure(new HttpException(response.code(), "网络错误"));
            }
        }
    }

    // 集中处理成功响应
    private void handleSuccessfulResponse(String result, HttpCallback callback) {
        try {
            JSONObject json = JSONObject.parseObject(result);
            if (json == null || !json.containsKey(_CODE)) {
                if (callback != null) {
                    callback.onFailure(new HttpException(-1, "无效响应格式"));
                }
                return;
            }

            String code = json.getString(_CODE);
            Boolean success = handleReqResult(appContext, code);
            if (success == null) return; // 已处理跳转登录等逻辑

            if (callback != null) {
                callback.onSuccess(result);
            }
        } catch (Exception e) {
            if (callback != null) {
                callback.onFailure(new HttpException(-1, "数据解析错误"));
            }
        }
    }

    /**
     * 对请求成功的数据处理
     *
     * @param activity
     * @param code
     * @return
     */
    private Boolean handleReqResult(Activity activity, String code) {
        HttpStatusEnum httpStatus = HttpStatusEnum.getInstance(Integer.parseInt(code));
        if (!httpStatus.ok()) {
            //code = 401 未登录跳转登录页面
            if (HttpStatusEnum.UNAUTHORIZED == httpStatus) {
                logout(activity);
                navigateTo(activity, LoginActivity.class,
                        Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                return null;
            }
            return false;
        }
        return true;
    }

    private String executeSync(Request request) throws HttpException {
        Call call = null;
        Response response = null;
        try {
            call = client.newCall(request);
            response = call.execute();
            if (!response.isSuccessful()) {
                throw new HttpException(response.code(), handleHttpError(response.code()));
            }
            return response.body() == null ? "" : response.body().string();
        } catch (IOException e) {
            throw handleException(e);
        } finally {
            // 确保资源释放
            if (response != null) {
                response.close();
            }
            if (call != null && !call.isCanceled()) {
                call.cancel();
            }
        }
    }

    // ==================== 异常处理方法 ====================

    private HttpException handleException(IOException e) {

        if (e instanceof SocketTimeoutException) {
            if (e.getMessage() != null && e.getMessage().contains("Global timeout")) {
                return new HttpException(408, "总请求超时，请检查网络");
            }
            return new HttpException(408, "请求超时，请检查网络");
        } else if (e instanceof ConnectException) {
            return new HttpException(503, "无法连接服务器");
        } else if (e instanceof UnknownHostException) {
            return new HttpException(502, e.getMessage());//域名解析失败
        } else if (e instanceof SSLHandshakeException) {
            return new HttpException(495, "安全证书验证失败");
        } else {
            return new HttpException(-1, "网络错误: " + e.getMessage());
        }
    }

    private String handleHttpError(int code) {
        switch (code) {
            case 400:
                return "请求参数错误";
            case 401:
                return "未授权，请登录";
            case 403:
                return "拒绝访问";
            case 404:
                return "请求地址不存在";
            case 408:
                return "请求超时";
            case 500:
                return "服务器内部错误";
            case 502:
                return "无效的网关";
            case 503:
                return "服务不可用";
            case 504:
                return "网关超时";
            default:
                return "HTTP错误: " + code;
        }
    }

    // ==================== 自定义拦截器 ====================

    /**
     * 重试拦截器（最大重试3次）
     */
    private static class RetryInterceptor implements Interceptor {
        private final int maxRetryCount;
        private final long baseRetryDelayMs;
        private final String TAG = "网络请求拦截器";

        public RetryInterceptor(int maxRetryCount, long baseRetryDelayMs) {
            this.maxRetryCount = maxRetryCount;
            this.baseRetryDelayMs = baseRetryDelayMs;
        }

        @NonNull
        @Override
        public Response intercept(@NonNull Chain chain) throws IOException {
            Request originalRequest = chain.request();
            // 禁用自动取消
            Call call = chain.call();
            if (call.isCanceled()) {
                throw new IOException("Call was already canceled");
            }
            IOException lastException = null;
            // 指数退避重试 (3-5次)
            for (int retryCount = 1; retryCount <= maxRetryCount; retryCount++) {
                Response response;
                try {
                    response = chain.proceed(originalRequest);
                    if (response.isSuccessful()) {
                        return response;
                    }
                    // 5xx服务器错误也重试
                    if (response.code() < 500) {
                        return response; // 4xx客户端错误不重试
                    }
                    response.close();
                } catch (IOException e) {
                    lastException = e;
                    // 在重试前检查网络
                    if (!CommonUtils.isNetworkConnected(instance.appContext)) {
                        throw new IOException("网络不可用");
                    }
                    if (shouldRetry(e)) {
                        Log.e(TAG, String.format("重试 %d/%d 次，异常：%s 访问地址： %s", retryCount, maxRetryCount, e.getClass().getSimpleName() + ":" + e.getMessage(), originalRequest.url()));
                        // 指数退避延迟：1s, 2s, 4s...
                        long delayMs = baseRetryDelayMs * (1L << (retryCount - 1));
                        try {
                            Thread.sleep(delayMs);
                        } catch (InterruptedException ie) {
                            Thread.currentThread().interrupt();
                            throw new IOException("网络请求重试中断(Retry interrupted)", ie);
                        }
                        continue;
                    }
                    break;
                }
            }
            lastException = lastException != null ? lastException : new IOException("未知网络错误");
            Log.e(TAG, lastException.getClass().getSimpleName() + " Message：" + Objects.requireNonNull(lastException.getMessage()));
            throw lastException;
        }

        // 判断哪些异常需要重试
        private boolean shouldRetry(IOException e) {
            // 需要重试的错误消息
            boolean isRetryMessage = e.getMessage() != null &&
                    (e.getMessage().contains("Socket closed") ||
                            e.getMessage().contains("Canceled") ||
                            e.getMessage().contains("reset") ||
                            e.getClass().getSimpleName().contains("IOException") ||
                            e.getMessage().contains("timeout"));
            // 需要重试的异常
            boolean isRetryException = e instanceof SocketTimeoutException || // 超时
                    e instanceof ConnectException ||      // 连接失败
                    e instanceof SSLHandshakeException || // SSL握手失败
                    (e.getCause() instanceof SSLException) || // SSL相关
                    e instanceof UnknownHostException;   // DNS解析失败
            return isRetryMessage || isRetryException;

        }

    }

    /**
     * 公共参数拦截器
     */
    private static class CommonParamsInterceptor implements Interceptor {
        private final Context context;

        public CommonParamsInterceptor(Context context) {
            this.context = context;
        }

        @NonNull
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request original = chain.request();
            // 添加公共参数
            HttpUrl url = original.url().newBuilder()
                    .addQueryParameter("device_id", getDeviceId())
                    .addQueryParameter("os_version", Build.VERSION.RELEASE)
                    .addQueryParameter("app_version", getAppVersion())
                    .addQueryParameter("timestamp", String.valueOf(System.currentTimeMillis()))
                    .build();
            // 添加公共头
            Request request = original.newBuilder()
                    .url(url)
                    .header("User-Agent", getUserAgent())
                    .header("Accept", "application/json")
                    .header(_TOKEN, CommonUtils.findFromSp(context, _TOKEN))
                    .method(original.method(), original.body())
                    .build();

            return chain.proceed(request);
        }

        @SuppressLint("HardwareIds")
        public String getDeviceId() {
            // 实现获取设备ID的逻辑
            return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        }

        public String getAppVersion() {
            try {
                return context.getPackageManager()
                        .getPackageInfo(context.getPackageName(), 0)
                        .versionName;
            } catch (Exception e) {
                return "unknown";
            }
        }

        private String getUserAgent() {
            return "Android/" + Build.VERSION.RELEASE + " " +
                    Build.MANUFACTURER + "/" + Build.MODEL +
                    " App/" + getAppVersion();
        }
    }

    /**
     * 日志拦截器（简化版）
     */
    private static class LoggingInterceptor implements Interceptor {
        @NonNull
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            long startTime = System.nanoTime();
            Response response = chain.proceed(request);
            long elapsedTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
            return response;
        }
    }

    // ==================== 回调接口和异常类 ====================

    public interface HttpCallback {
        void onSuccess(String response);

        void onFailure(HttpException e);
    }

    public static class HttpException extends Exception {
        private final int errorCode;

        public HttpException(int errorCode, String message) {
            super(message);
            this.errorCode = errorCode;
        }

        public int getErrorCode() {
            return errorCode;
        }

        @NonNull
        @Override
        public String toString() {
            return "HttpException{" +
                    "errorCode=" + errorCode +
                    ", message='" + getMessage() + '\'' +
                    '}';
        }
    }

    /**
     * 自定义DNS解析（解决DNS查询超时）
     */
    private static class CustomDns implements Dns {
        private final int timeout;
        private final Dns systemDns;

        public CustomDns(int timeoutSeconds) {
            this.timeout = timeoutSeconds;
            this.systemDns = Dns.SYSTEM;
        }

        @NonNull
        @Override
        public List<InetAddress> lookup(@NonNull String hostname) throws UnknownHostException {
            ExecutorService executor = Executors.newSingleThreadExecutor();
            try {
                Future<List<InetAddress>> future = executor.submit(() -> systemDns.lookup(hostname));
                return future.get(timeout, TimeUnit.SECONDS);
            } catch (TimeoutException e) {
                throw new UnknownHostException("DNS查询超时 " + hostname);
            } catch (Exception e) {
                throw new UnknownHostException("DNS查询失败: " + hostname + " msg:" + e.getMessage());
            } finally {
                executor.shutdownNow();
            }
        }
    }

    /**
     * 网络可用性检查拦截器 网络状态检测（提前失败）
     */
    private static class NetworkCheckInterceptor implements Interceptor {
        private final Context context;

        public NetworkCheckInterceptor(Context context) {
            this.context = context.getApplicationContext();
        }

        @NonNull
        @Override
        public Response intercept(@NonNull Chain chain) throws IOException {
            if (!CommonUtils.isNetworkConnected(context)) {
                throw new NoNetworkException();
            }
            return chain.proceed(chain.request());
        }
    }

    // 自定义无网络异常
    private static class NoNetworkException extends IOException {
        public NoNetworkException() {
            super("无可用网络连接");
        }
    }
}
